/*
 * @Author: Karl Liris
 * @Date: 2021-02-26 08:48:30
 * @LastEditTime: 2021-03-17 08:46:02
 */
'use strict'

import { startsWith } from 'lodash';
import {
  app,
  protocol,
  BrowserWindow,
  ipcMain,
} from 'electron';
import { autoUpdater } from 'electron-updater';
import log from 'electron-log';
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib';
const isDevelopment = process.env.NODE_ENV !== 'production';
import http from 'http';
import net from 'net';

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
]);

let updateEvent = null;

function reply(event, data) {
  if (updateEvent) {
    updateEvent.reply(event, data);
  }
}

function autoUpdate() {
  autoUpdater.logger = log;
  autoUpdater.logger.transports.file.level = 'info';
  autoUpdater.autoInstallOnAppQuit = true;
  autoUpdater.setFeedURL('http://192.168.8.134:3000/proxytools/');
  autoUpdater.on('error', (error) => {
    reply('update-error', error);
  });
  autoUpdater.on('checking-for-update', (message) => {
    reply('update-checking', message);
  });
  autoUpdater.on('update-available', (message) => {
    reply('update-available', message);
  });
  autoUpdater.on('update-not-available', (message) => {
    reply('update-not-available', message);
  });
  autoUpdater.on('download-progress', (progress) => {
    reply('update-progress', progress);
  });
  autoUpdater.on('update-downloaded', (release) => {
    reply('update-downloaded', release);
    autoUpdater.quitAndInstall();
  });
}

async function createWindow() {
  // Create the browser window.
  let win = new BrowserWindow({
    width: 310,
    height: 500,
    center: true,
    resizable: false,
    show: false,
    useContentSize: true,
    autoHideMenuBar: true,
    frame: false,
    webPreferences: {
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION
    }
  })

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    win.loadURL('app://./index.html')
  }

  win.on('closed', () => {
    win = null;
  });

  win.once('ready-to-show', () => {
    win.show();
  })
}

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
  createWindow();
  autoUpdate();
})

app.setLoginItemSettings({
  openAtLogin: true,
  openAsHidden: false,
  path: process.execPath,
});

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}

function portIsOccupied(port, success = () => {}, error = () => {}) {
  const server = net.createServer().listen(port);
  server.on('listening', () => {
    server.close();
    success();
  });
  server.on('error', (err) => {
    error(err);
  });
}

ipcMain.on('closeWindow', () => {
  app.quit();
});

let httpServer = null;

ipcMain.on('toggleServer', (event, config) => {
  if (httpServer) {
    httpServer.close();
    httpServer = null;
    event.reply('toggleServer', false);
  } else {
    portIsOccupied(config.serverPort, () => {
      httpServer = http.createServer((req, res) => {
        const { url, method, headers } = req;
        const { path, protocol, host, port } = config;
        if (url !== '/favicon.ico' && startsWith(url, path)) {
          const preq = http.request({
            protocol,
            host,
            port,
            method,
            path: url,
            json: true,
            headers,
          }, (pres) => {
            pres.on('data', (chunk) => {
              res.write(chunk, 'binary');
            });
            pres.on('end', () => {
              res.end();
            });
            res.writeHead(pres.statusCode, pres.headers);
          });
          req.on('data', (chunk) => {
            preq.write(chunk, 'binary');
          });
          req.on('end', () => {
            preq.end();
          });
        } else {
          res.end(url);
        }
      });
      httpServer.listen(config.serverPort);
      event.reply('toggleServer', true);
    }, () => {
      event.reply('toggleServer', false);
    });
  }
});